# -*- coding:utf-8 -*-
from ast import If, Or
from crypt import METHOD_SHA256
import json
import pandas as pd
from STool.StockTool import StockTool
from STool.StockTT import *
import copy
import os,shutil
import numpy as np; 
import operator

class StockChart:
    def __init__(self,sql):
        self.mysql = sql
        self.rps_count =""
        self.today_string= StockTool.getTodayString()


    def isMA5HighMA20(self,stock_info):
        
        
        
        ts_code = stock_info["ts_code"]
        trade_daily=stock_info['trade_daily']
        ma5 = stock_info["ma5"]
        ma30 = stock_info["ma30"]
        ma60 = stock_info["ma60"]

        MA5=[float(a) for a in ma5.split(",")]                   
        MA30=[float(a) for a in ma30.split(",")]     
        MA60=[float(a) for a in ma60.split(",")]     


        if ts_code==None and trade_daily==None:
            print("参数异常")
            exit(0)
            
        if trade_daily == None:
            print("日线议程")
            a=self.mysql.getStockInfoWith(ts_code)
            trade_daily=a['trade_daily']

        df = pd.DataFrame(trade_daily)
        CLOSE=df.close.values;  
        OPEN=df.open.values     

        percent=trade_daily[0]['percent']
        percent1=trade_daily[1]['percent']
        percent2=trade_daily[2]['percent']
        
        vol=trade_daily[0]['vol']
        vol1=trade_daily[1]['vol']
        vol2=trade_daily[2]['vol']

      
        # MA5日线上穿MA60,涨幅大于7,放量突破
        if MA5[0] >= MA60[0] and MA5[1] < MA60[1] and percent >=7 and vol > vol1*1.3:
            return True

        isValue = True
        #收盘价小于MA100放弃
        if len(MA60)>0 and CLOSE[0]< MA60[0]:
            print("%s %s 当前股价低于60日线" %(stock_info['name'],ts_code))
            return False


        # # 连续两天5日线在MA20下放弃
        if MA5[0] <  MA30[0] and MA5[1] <  MA30[1] and  CLOSE[0]< MA5[0]:
            print("%s %s 连续两天当前5日线低于20日线，收盘价低于5日线" %(stock_info['name'],ts_code))
            return False

        if MA5[0] <  MA60[0]:
            print("%s %s 当前20日线低于60日线" %(stock_info['name'],ts_code))
            return False
        
        #连阴三天放弃
        if (percent < -5 and percent1 < -5 and percent2 < -5) or (percent <-5 and percent1 < -5):
            print("%s %s 连续三天大阴线" %(stock_info['name'],ts_code))
            return False
        
        if percent < -5 and percent2 < -5:
            print("%s %s 两大阴夹一阳" %(stock_info['name'],ts_code))
            return False
 
        #巨量大阴线
        if CLOSE[0]<OPEN[0]*0.95:
            print("%s %s 巨量大阴线" %(stock_info['name'],ts_code))
            return False
            
     
        return isValue 
    
    
    def isMA5HighMA20_MA100(self,th_code=None,trade_daily=None):
        if th_code==None and trade_daily==None:
            print("参数异常")
            exit(0)
            
        if trade_daily == None:
            stock_info=self.mysql.getStockInfoWith(th_code)
            trade_daily=stock_info['trade_daily']
        
        df = pd.DataFrame(trade_daily)
        CLOSE=df.close.values; 
        
        sort_df = df.sort_index(ascending=False)
        CLOSE_MACD=sort_df.close.values; 
        CLOSE_KDJ=sort_df.close.values; 
        HIGH_KDJ=sort_df.high.values; 
        LOW_KDJ=sort_df.low.values; 

        
            
        
        MA5=MA(CLOSE,5) 
        MA20=MA(CLOSE,20)   
        MA60=MA(CLOSE,60) 
        
        a=all(operator.gt(MA5[0:5],MA60[0:5]))
        b=all(operator.gt(MA20[0:5],MA60[0:5]))
        c=all(operator.gt(MA5[0:5],MA20[0:5]))

        DIF,DEA,SMACD = MACD(CLOSE_MACD)

        K,D,J = KDJ(CLOSE_KDJ,HIGH_KDJ,LOW_KDJ)

        mingz = False  
        if c:
            mingz = True

        if DIF[-1] >0 and DEA[-1] >0 and DIF[-1] < 0.8:
            if J[-1]>=K[-1] and K[-1]>=D[-1] and J[-1]>=J[-2]:
                mingz = True
            else:
                mingz = False
        else:
            mingz = False
        if DEA[-1] < DEA[-2] and DEA[-2] < DEA[-3] and DEA[-3] < DEA[-4] and DEA[-4] < DEA[-5] and DEA[-5] < DEA[-6]:
            mingz = False
        
        if J[-1] < J[-2] and J[-2] < J[-3]:
            mingz = False
               
        if CLOSE[0] < MA20[0]:
            mingz = False  
            
        if CLOSE[0] < MA60[0]:
            mingz = False 

        return mingz 
                   


    def delUnuseKey(self,stock_info_):
        stock_info = copy.deepcopy(stock_info_)
        
        ts_code = stock_info['ts_code']

        hy= stock_info["hy"]
        hy2= stock_info["hy2"]
        hy3= stock_info["hy3"]
        AA=[]
        if hy==hy2:
            AA=[hy]
        else:
            AA=[hy,hy2]
            
        hangye="-".join(UNIQUE(AA))

        stock_info['hangye']=hangye
        stock_info['circ_mv']=str(round(float(stock_info['circ_mv']),2))+"亿"
        stock_info['percent']=str(round(float(stock_info['percent']),2))+"%"
        stock_info['shebao_ORG']=str(round(float(stock_info['shebao_ORG']),2))+"%"
        stock_info['huanshou']=str(round(stock_info["huanshou"],2))+"%"
        stock_info['jijin_ORG']=str(round(float(stock_info['jijin_ORG']),2))+"%"
        stock_info['hk_ORG']=str(round(float(stock_info['hk_ORG']/100/10000),2))+"万"
        if not "万" in str(stock_info['net_mf_amount']):
            stock_info['net_mf_amount'] = str(stock_info['net_mf_amount'])+"万"
            
                    
        del stock_info['trade_daily']
        del stock_info['list_date_days']
        del stock_info['is20Wave']
        del stock_info['avail_5']
        del stock_info['avail_20']
        del stock_info['avail_60']
        del stock_info['avail_250']
        del stock_info['is20High']
        # del stock_info['rps250']
        del stock_info['qfii_ORG']
        return stock_info


    def buildStocksMaAndMtMA100(self,stocks_rps,bankuai_mt_dic):
        stocks_rps=stocks_rps.loc[stocks_rps['hy'].str.contains("|".join(list(bankuai_mt_dic.keys())))]
        stocks_rps_array=stocks_rps.to_dict(orient='records')
        print("**** %s" %(len(stocks_rps_array)))
        stocks=[stock_info["ts_code"] for stock_info in stocks_rps_array if self.isMA5HighMA20_MA100(stock_info["ts_code"],stock_info["trade_daily"])]
        print("**** %s" %(len(stocks)))
        return stocks

    def buildStocksMaAndMt(self,stocks_rps,bankuai_mt_dic,rps_count,type='rps'):
        rpskey='rps'+str(rps_count)
        self.rps_count=rps_count
        #检索符合mt板块的股票
        stocks_rps=stocks_rps.loc[stocks_rps['hy'].str.contains("|".join(list(bankuai_mt_dic.keys())))]
        stocks_rps_array=stocks_rps.to_dict(orient='records')

        #按照板块分组
        stock_arr_bankuai=StockTool.remakeStocksGroupByBK(stocks_rps_array,'bk')
        stock_table = []
        stock_table_98 = []

        for bk,stocks in stock_arr_bankuai.items():
            print(bk)
            print(len(stocks))
            print("\n")
            stocks=[stock_info for stock_info in stocks if self.isMA5HighMA20(stock_info)]
            stocks = sorted(stocks, key=lambda item:item[rpskey] ,reverse = True)#行业股票数据根据最新日期rps排序
            
            if len(stocks) > 0 and int(stocks[0][rpskey])>=95: #最高RPS是否大于95
                for index,stock_info_dic in enumerate(stocks):
                    stock_info = self.delUnuseKey(stock_info_dic)
                    stock_info[rpskey]=round(stock_info[rpskey],2)
                    if round(stock_info[rpskey],2) >=95 and rps_count <= 5:
                        stock_table.append(stock_info) 
                        stock_table_98.append(stock_info) 
                    else:
                        stock_table.append(stock_info) 

                           
        print("符合 RPS>90 数据 %s" %(len(stock_table)))
        print("\n")
        
        
        value_stocks={}
        stocks_arr_hy=StockTool.remakeStocksGroupByBK(stock_table,'bk')
        for bk,stocks in stocks_arr_hy.items():
            dic = {}
            dic['stock_count']=len(stocks)
            dic['stock_array']=stocks
            value_stocks[bk]=dic
    
                
        value_stocks=sorted(value_stocks.items(),key=lambda item:item[1]['stock_count'] ,reverse = True)
        #     value_stocks[bk]=bk_stock_array
        return [stock_table,value_stocks,stock_table_98]
